package com.cn.qgx428.lazydiary.ui.activity.subActivity

import android.content.Context
import android.graphics.Color
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v7.widget.LinearLayoutManager
import android.widget.ImageView
import android.widget.TextView
import com.cn.qgx428.lazydiary.Presenter.BillPresenter
import com.cn.qgx428.lazydiary.R
import com.cn.qgx428.lazydiary.Utils.MConst
import com.cn.qgx428.lazydiary.Utils.RecordHelper
import com.cn.qgx428.lazydiary.adapter.RAdapter
import com.cn.qgx428.lazydiary.adapter.RViewHolder
import com.cn.qgx428.lazydiary.db.bean.CBill
import com.cn.qgx428.lazydiary.db.dao.BillDao
import com.cn.qgx428.lazydiary.ui.activity.BaseActivity
import com.github.mikephil.charting.charts.PieChart
import com.github.mikephil.charting.components.Description
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import kotlinx.android.synthetic.main.activity_bill_statistic.*
import org.jetbrains.anko.toast
import java.text.DecimalFormat

class BillStatisticActivity : BaseActivity() {

    lateinit var where:String
    lateinit var options: List<TextView>
    lateinit var pie: PieChart
    // 月份账单
    lateinit var bills: MutableList<CBill>
    // 收入
    val incomeBills: MutableList<TotalBill> = mutableListOf()
    // 支出
    val expendBills: MutableList<TotalBill> = mutableListOf()
    // 收入与支出
    val totalBills: MutableList<TotalBill> = mutableListOf()
    //
    var currentType = MConst.BILL_EXPEND

    val adapter = TotalAdapter(this, expendBills, R.layout.adapter_bill_statistic_re)

    override fun initUI() {
        hindActionBar()
        setStatuBarColor(Color.BLACK)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bill_statistic)
        initView()
        getBillsInfo()
        changePie(expendBills,
                "总支出 "+totalBills.get(1).total.toString(),
                MConst.expendTextColor)
    }

    private fun getBillsInfo() {
        bills = BillDao().queryWhereLike("createTime",where) as MutableList<CBill>
        log(bills.size.toString())
        var expendTotal = 0f
        var incomeTotal = 0f
        bills.forEach {
            // 收入类型
            if (it.type.equals(MConst.BILL_INCOME)){
                getItemTotalBill(incomeBills, it.specific).total += it.total!!.toFloat()
                incomeTotal += it.total?.toFloat()!!
            }
            // 支出类型
            else{
                getItemTotalBill(expendBills, it.specific).total += it.total!!.toFloat()
                expendTotal += it.total?.toFloat()!!
            }
        }
        totalBills.add(TotalBill("收入",incomeTotal))
        totalBills.add(TotalBill("支出",expendTotal))

        log(expendBills.size.toString())
        log(expendBills.toString())
        adapter.currentTotalAccount = expendTotal
        adapter.currentType = MConst.BILL_EXPEND
        adapter.setDatas(expendBills)
    }

    /**
     * 定位单个TotalBill
     */
    private fun getItemTotalBill(bills: MutableList<TotalBill>, specific: String): TotalBill{
        bills.forEach {
            if (it.specific.equals(specific))
                return it
        }

        // 定位不到，添加新的bill
        val newBill = TotalBill(specific)
        bills.add(newBill)
        return  newBill
    }

    private fun initView() {
        options = listOf<TextView>(
                billStatistic_income,
                billStatistic_expend,
                billStatistic_summarize
        )
        options.forEach {
            it.setOnClickListener({
                changeOptionStyle(it as TextView)
                changeUIData(it.text.toString())
            })
        }
        billStatistic_back.setOnClickListener({finish()})
        where = intent.getStringExtra(MConst.CURRENT_MOUTH_WITH_YEAR)
        billStatistic_mouth.text = where
        billStatistic_re.layoutManager = LinearLayoutManager(this)
        billStatistic_re.adapter = adapter

        pie = billStatistic_pie
        pie.description = Description()
        pie.description.text = ""
        pie.setHoleColor(Color.WHITE)
        pie.isDrawHoleEnabled = true
        pie.holeRadius = 70f
//        pie.setDrawCenterText(true)
//        pie.isDrawHoleEnabled = true
        pie.setDrawEntryLabels(false)

//        pie.setCenterTextColor(R.color.mYaHei)
//        pie.centerText = "中心哦"
//
//        val lg = pie.legend
//        lg.direction = Legend.LegendDirection.LEFT_TO_RIGHT
//        lg.position = Legend.LegendPosition.RIGHT_OF_CHART
//
//        val pieEntry: MutableList<PieEntry> = mutableListOf()
//        for (i in 0..5){
//            val entry = PieEntry(2f + i,"试试" + i.toString())
//            pieEntry.add(entry)
//        }
//        val pieDateSet = PieDataSet(pieEntry,"")
//        pieDateSet.setColor(R.color.mDarkTurquoise)
//        pieDateSet.sliceSpace = 2.0f
//        val pieData = PieData()
//        pieData.dataSet = pieDateSet
//        pie.data = pieData
    }

    private fun changeUIData(type: String) {
        when(type){
            MConst.BILL_INCOME-> {
                currentType = MConst.BILL_INCOME
                changePie(incomeBills,
                        "总收入 "+ totalBills.get(0).total.toString(),
                        MConst.incomeTextColor)
                adapter.currentType = MConst.BILL_INCOME
                adapter.currentTotalAccount = totalBills.get(0).total
                adapter.setDatas(incomeBills)
            }
            MConst.BILL_EXPEND-> {
                currentType = MConst.BILL_EXPEND
                changePie(expendBills,
                        "总支出 "+totalBills.get(1).total.toString(),
                        MConst.expendTextColor)
                adapter.currentType = MConst.BILL_EXPEND
                adapter.currentTotalAccount  = totalBills.get(1).total
                adapter.setDatas(expendBills)
            }
            MConst.BILL_SUMMERISE-> {
                currentType= MConst.BILL_SUMMERISE
                changePie(totalBills,
                        "结余 " + (totalBills.get(0).total - totalBills.get(1).total).toString(),
                        MConst.billSummerizeTextColor)
                adapter.currentType = MConst.BILL_SUMMERISE
                adapter.currentTotalAccount = totalBills.get(0).total + totalBills.get(1).total
                adapter.setDatas(totalBills)
            }
        }
    }

    private fun changePie(totalBills: List<TotalBill>, centryPrump: String, centryTextCorlor: Int){
        pie.centerText = centryPrump
        pie.setCenterTextColor(centryTextCorlor)

        // 装配数据
        val pieEntries: MutableList<PieEntry> = mutableListOf()
        totalBills.forEach {
            val entry = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                PieEntry(it.total, "",
                        getDrawable(RecordHelper.getBillIcon(currentType,it.specific)))
            } else {
                PieEntry(it.total, R.drawable.ic_normal)
            }
            pieEntries.add(entry)
        }
        val pieDataSet = PieDataSet(pieEntries, "")
        pieDataSet.sliceSpace = 2.0f
        // 设置圆环每个成分颜色， 目前是统一的
        pieDataSet.color = Color.BLACK
        val pieDate = PieData()
        pieDate.dataSet = pieDataSet
        pie.data = pieDate
        pie.invalidate()
    }

    private fun changeOptionStyle(textView: TextView) {

        options.forEach {
            if (it == textView){
                it.setTextColor(resources.getColor(R.color.colorAccent))
                it.setBackgroundResource(R.drawable.activity_bill_statistic_option_select)
            } else{
                it.setTextColor(resources.getColor(R.color.mWhite))
                it.setBackgroundResource(R.drawable.activity_bill_statistic_option_unselect)
            }
        }
    }

    // 存储每月账单的单类型消费的总值
    data class TotalBill(var specific:String, var total: Float = 0f)

    class TotalAdapter: RAdapter<TotalBill>{

        // 当前类型
        public var currentType = MConst.BILL_EXPEND
        // 当前百分比总额
        public var currentTotalAccount = 0f
        // 小数点格式
        val dFormat = DecimalFormat("0.00")

        override fun conver(holder: RViewHolder, data: TotalBill) {
            val icon = holder.getView<ImageView>(R.id.adapter_billStatistic_specificIcon)
            val percent = holder.getView<TextView>(R.id.adapter_billStatistic_percent)
            val specific = holder.getView<TextView>(R.id.adapter_billStatistic_specific)
            val total = holder.getView<TextView>(R.id.adapter_billStatistic_total)

            total?.text = data.total.toString()
            specific?.setText(data.specific)
            icon?.setImageResource(RecordHelper.getBillIcon(currentType,data.specific))

            val value = dFormat.format(data.total / currentTotalAccount * 100)
            percent?.text = value.toString() + "%"
        }

        constructor(context: Context, bills: MutableList<TotalBill>, layoutId: Int )
                :super(context, layoutId, bills)
    }
}
